import {useEffect, useState} from "react";
import {Question, Star} from "../../types";
import {useAtom} from "jotai";
import {selectedIdsAtom, starCurrentPageAtom, starPageSizeAtom} from "../../store/atoms";
import toast, {Toaster} from "react-hot-toast";
import BaseStarItem from "./BaseStarItem";

interface Props {
    className?: string
}

function StarPageList({className = ''}: Props) {
    const [currentPage] = useAtom(starCurrentPageAtom)
    const [pageSize] = useAtom(starPageSizeAtom)
    const [selectedIds, setSelectedIds] = useAtom(selectedIdsAtom)
    const [starList, setStarList] = useState<Star[]>([]);
    useEffect(() => {
        const offset = (currentPage - 1) * pageSize;
        window.ipcRender.invoke('star:getList', {
            limit: pageSize,
            offset: offset,
        }).then((res) => {
            setStarList(res);
            console.log("当前页收藏试卷id列表:", res.map((s: Star) => s.id));
        })
    }, [currentPage, pageSize]);

    // 删除收藏
    const toggleSelectedIds = (id: number) => {
        toast.promise(
            async () => {
                const res =  await window.ipcRender.invoke('star:removeItem', {
                    id: id,
                });
                return res;
            },
            {
                loading: '处理中...',
                success: '取消成功',
                error: (err) => `取消失败：${err.message}`,
            }
        ).then(() => {
            const newList = starList.filter(s => s.id !== id);
            setStarList(newList);
            console.log('Removed:', id, 'Result:', starList);
        })
    }

    return (
        <div className={`m-2 ${className}`}>
            <Toaster
                reverseOrder={true}
                toastOptions={{
                    duration: 1000,
                    error: {
                        duration: 2000,
                    },
                    success: {
                        duration: 2000,
                    }
                }}
            />
            {starList.map((star) => (
                <div key={star.id} className="flex items-start gap-2">
                    {/* 左侧加号按钮 */}
                    <button className="btn btn-square mt-5 text-md "
                            onClick={() => {
                                const idsToAdd = (star.ques_ids || '')
                                    .split(',')
                                    .map(s => s.trim())
                                    .map(s => Number(s.trim()))
                                    .filter(n => !isNaN(n));
                                console.log(`添加考题id：${idsToAdd}`);
                                setSelectedIds(prev => [
                                    ...prev,
                                    ...idsToAdd.filter(id => !prev.includes(id))
                                ])
                                toast.success("考题已添加");
                            }}
                    >
                        <span className="fa fa-plus " aria-hidden="true"/>
                    </button>
                    {/* 记录信息 */}
                    <div className="flex-1">
                        <BaseStarItem
                            className="flex items-start gap-2"
                            star={star}
                        />
                    </div>
                    {/* 右侧删除按钮 */}
                    <button className="btn btn-square btn-error text-error-content mt-5"
                            onClick={() => toggleSelectedIds(star.id)}>
                        <span className="fa fa-trash fa-lg"/>
                    </button>
                </div>
            ))}
        </div>
    )
}

export default StarPageList;